package com.example.zy5.demos.web.test5;

import com.rabbitmq.client.*;
import com.rabbitmq.client.Connection;
import java.sql.*;

public class LogConsumer {
    private final static String QUEUE_NAME = "logQueue";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost"); // RabbitMQ 服务主机
        try (Connection connection = factory.newConnection();
             Channel channel = connection.createChannel()) {
            channel.queueDeclare(QUEUE_NAME, true, false, false, null);
            DeliverCallback deliverCallback = (consumerTag, delivery) -> {
                String message = new String(delivery.getBody(), "UTF-8");
                System.out.println(" [x] Received '" + message + "'");
                storeLogToDatabase(message);
            };
            channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> {});
        }
    }
    private static void storeLogToDatabase(String message) {
        String url = "jdbc:mysql://localhost:3306/lyt";
        String username = "root";
        String password = "lyt20031229";

        String query = "INSERT INTO logs (message) VALUES (?)";
        try (java.sql.Connection conn = DriverManager.getConnection(url, username, password);
             PreparedStatement stmt = conn.prepareStatement(query)) {

            stmt.setString(1, message);
            stmt.executeUpdate();
            System.out.println("Log stored in database: " + message);

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
